<?php
/**
 * Created by PhpStorm.
 * User: xuho
 * Date: 2020-02-15
 * Time: 19:37
 */

namespace app\cdc\validate\admin;


use app\common\model\mysql\AccountModel;
use app\common\model\mysql\GroupModel;

class GroupValidate extends \app\common\validate\BaseValidate
{
    protected $rule = [
        'parent_id' => 'require',
        'name' => 'require|checkName',
        'status' => 'require',
        'group_id' => 'require',
    ];

    protected $message = [
        'parent_id.require' => '请选择 父级',
        'name.require' => '请输入 名称',
        'status.require' => '请选择 状态',
    ];

    protected $scene = [
        'save' => ['parent_id', 'name', 'rule_ids', 'status'],
        'update' => ['parent_id', 'name', 'rule_ids', 'status'],
        'rule' => [''],
        'delete' => ['']
    ];

    public function sceneDelete()
    {
        return $this->only(['id'])
            ->append('id', 'checkParentId|checkGroupId');
    }

    protected function checkName($value, $rule, $data = [])
    {
        $where[] = ['name', '=', $data['name']];
        !empty($data['id']) ? $where[] = ['id', '<>', $data['id']] : false;
        if (GroupModel::checkRowExists($where)) {
            return '组名已存在';
        }
        return true;
    }

    protected function checkParentId($value, $rule, $data = [])
    {
        if (GroupModel::checkRowExists(['parent_id' => $data['id']])) {
            return '不能删除含有子级和管理员的组';
        }
        return true;
    }

    public function checkGroupId($value, $rule, $data = [])
    {
        if (AccountModel::whereFindInSet('group_ids',$data['id'])->find()) {
            return '不能删除含有子级和管理员的组';
        }
        return true;
    }
}